package shiyan1;

/**
 * Created by zhangyunqi on 2017/6/7.
 */

import java.util.*;

public class MyDC {
    /**
     * constant for addition symbol
     */
    private final char ADD = '+';
    /**
     * constant for subtraction symbol
     */
    private final char SUBTRACT = '-';
    /**
     * constant for multiplication symbol
     */
    private final char MULTIPLY = '*';
    /**
     * constant for division symbol
     */
    private final char DIVIDE = '/';
    /**
     * the stack
     */
    private Stack <Integer> stack;

    public int evaluate(String postfix) {

        Stack <Integer> stack = new Stack ();
        int i = 0, result = 0;
        while (i < postfix.length ()) {
            char ch = postfix.charAt ( i );
            if (ch >= '0' && ch <= '9') {
                result = 0;
                while (ch != ' ') {
                    result = result * 10 + Integer.parseInt ( ch + "" );
                    i++;
                    ch = postfix.charAt ( i );
                }
                i++;
                stack.push ( new Integer ( result ) );
            } else {
                int y = stack.pop ().intValue ();
                int x = stack.pop ().intValue ();
                switch (ch) {
                    case ADD:
                        result = x + y;
                        break;
                    case SUBTRACT:
                        result = x - y;
                        break;
                    case MULTIPLY:
                        result = x * y;
                        break;
                    case DIVIDE:
                        result = x / y;
                }
                stack.push ( new Integer ( result ) );
                i++;
            }
        }
        return stack.pop ().intValue ();
    }
}
